import { tablesInterface } from "@/common/interface/table.interface";
import TablePage from "@/components/TablePage/TablePage";
import { defineComponent, onMounted, onUnmounted, reactive, ref } from "vue";
import ProductListService from "./productList.service";
import { useRouter } from "vue-router";
import eventBus from "@/common/eventBus/mitt";
import Detail from "./Detail/Detail";

export default defineComponent({
  name: 'Index',
  setup() {
    const router = useRouter();
    const tablePageRef = ref(null as any);
    const productListService = new ProductListService();
    const tables = reactive({
      list: [
        {
          title: "产品列表",
          rowKey: "id",
          columns: [
            {
              title: "ID",
              dataIndex: "id",
              align: "center",
              width: "80px",
            },
            {
              title: "产品名称",
              dataIndex: "chineseName",
              align: "center",
              width: "280px",
            },
            {
              title: "产品英文名称",
              dataIndex: "englishName",
              align: "center",
              width: "280px",
            },
          ],
          toolbar: {
            left: ["refresh", "add"],
            right: ["filter"],
            add: {
              handler: () => {
                router.push(`/productManage/productAdd?type=add`)
              }
            },
          },
          searchForm: {},
          service: productListService,
          operation: ({ record }) => [
            {
              type: "edit",
              clickHandler: () => {
                router.push(`/productManage/productAdd?type=edit&id=${record.id}`)
              }
            },
            {
              type: 'detail',
              clickHandler: () => {
                const detailPopupRef = tablePageRef.value.getPopup("detailRef");
                detailPopupRef.value.open({ id: record.id });
              }
            },
            {
              type: "delete",
              clickHandler: "delete",
            },
          ],
          popups: [
            {
              ref: 'detailRef',
              dom: () => <Detail />
            }
          ],
          pagination: true,
          tableSourceFormat: {
            data: 'rows',
            pageSize: 'pageSize',
            current: 'pageNum',
          },
        }
      ],
    } as tablesInterface)
    const config = reactive({
      table: tables.list[0],
    })
    onMounted(() => {
      eventBus.productFinish.on(() => {
        tablePageRef.value.reload();
      })
    })

    onUnmounted(() => {
      eventBus.productFinish.off();
    })

    return () => (
      <TablePage ref={tablePageRef} config={config} />
    )
  }
})